package thread.lock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Store {
    private boolean flag = false;
    private String name;
    private int count = 1;
    private int MAX_SIZE = 50;
    List<Integer> list = new ArrayList<>();

    //创建锁对象
    Lock lock = new ReentrantLock();
    //获取监视器，把锁对象和监视器联系起来
    //获取生产者的监视器
    Condition ppp = lock.newCondition();
    //获取消费者的监视器
    Condition ccc = lock.newCondition();


    //生产商品的函数
    public void set(String name) {
        //获取锁
        lock.lock();
        try {
            //当有商品时，监视器等待
            while (list.size() > MAX_SIZE) {
                try {
                    ppp.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //当没有商品时,生产商品
            this.name = name;
            count++;
            //打印生产了哪个商品。
            System.out.println(Thread.currentThread().getName() + ".....生产了...." + this.name + "仓库库存:" + list.size());
            //将标记改为true
            list.add(count);
            //唤醒消费者监视器
            ccc.signal();
        } finally {
            //最后一定要释放锁对象
            lock.unlock();
        }
    }

    public void get() {
        //消费者首先要获取锁
        lock.lock();
        try {
            while (list.size() == 0) {
                try {
                    ccc.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + "...消费了第" + list.get(0) + this.name + "仓库库存:" + (list.size() - 1));
            list.remove(0);
            ppp.signal();
        } finally {
            lock.unlock();
        }
    }
}
